<?php
namespace App\Http\Controllers\AppApi\Pay;

use App\admin\Service\OA;
use App\Jobs\Fun;
use App\Models\LogModel;
use App\Services\OrdersPayService;
use App\Services\Pay\AlipayAppPack\AlipayApp;
use App\Services\Pay\AlipayPack\sdk\Alipay;
use Illuminate\Http\Request;
use App\Models\MoneyBilModel;
use DB;
class PayController extends BaseController
{
    protected $orderPayService;
    public $uid=0;
    public function __construct(OrdersPayService $orderPayService)
    {
        parent::__construct();
        $this->orderPayService = $orderPayService;
    }




    /**
     * 支付宝统一支付结果回调处理
     * @param Request $request
     * @return string
     */
    public function alipayNotifyApp(Request $request)
    {
        $tradeData = array_merge($_POST, $_GET);
        LogModel::add("alipayNotifyApp_POST:".json_encode($_POST));
        LogModel::add("alipayNotifyApp_GET:".json_encode($_GET));
        $status=false;
        $ali=new AlipayApp();
        if($ali->notify()) {
            $out_trade_no = $tradeData['out_trade_no'];
            $status = $this->chongzhisuccess($tradeData);
            LogModel::add("支付回调调用状态:" . $status);
            if(!$status){
                LogModel::add("this->msgerror:" . $this->msgerror);
            }
        }else{
            LogModel::add("支付回调调用失败:验证错误".json_encode($_POST), LogModel::typeError);
        }
        if($status){
            echo "success";
        }else{
            echo "fail";
        }
    }


    /**
     * 支付宝统一支付结果回调处理
     * @param Request $request
     * @return string
     */
    public function notify_alipay(Request $request)
    {
        $tradeData = array_merge($_POST, $_GET);
        LogModel::add("notify_alipay_POST:".json_encode($_POST));
        LogModel::add("notify_alipay_GET:".json_encode($_GET));
        $status=false;
        $ali=new Alipay();
        if($ali->notify()) {
            $out_trade_no = $tradeData['out_trade_no'];
          ///  if (strpos($out_trade_no, MoneyBilModel::DEL_cz) === 0) {///判断是否为充值订单
                $status = $this->chongzhisuccess($tradeData);
                LogModel::add("支付回调调用状态:" . $status);
                if(!$status){
                    LogModel::add("this->msgerror:" . $this->msgerror);
                }
           /* } else {
                $status = false;
                LogModel::add("支付回调调用失败:类型不支持".$out_trade_no, LogModel::typeError);
            }*/
        }else{
            LogModel::add("支付回调调用失败:验证错误".json_encode($_POST), LogModel::typeError);
        }
        if($status){
            echo "success";
        }else{
            echo "fail";
        }
    }






    /**
     * 支付宝统一支付结果回调处理
     * @param Request $request
     * @return string
     * @deprecated
     */
    private function alipayNotify_old(Request $request)
    { 
        exit('弃用');
        info('pay:alipay:parmer:' . json_encode($_POST));
        info('pay:GET:' . json_encode($_GET));
        LogModel::add('pay:alipay:parmer:' . json_encode($_POST));
        LogModel::add('pay:GET:' . json_encode($_GET));
        try {
            //参数处理
            $channel = trim($request->input('channel', 'm'));
            $type = intval($request->input('type', 1));
            if(!$channel || !$type){
                info('pay:支付失败，参数不全');

                LogModel::add('pay:支付失败，参数不全');
                return 'fail';
            }
  
            $tradeData = array_merge($_POST, $_GET);
             
            //调用方法
          $result = $this->orderPayService->alipayReceiveOrder($channel,$tradeData);
            if ($result) {
        
                $status=false;
                
                     $out_trade_no = $tradeData['out_trade_no']; 
                     if(strpos($out_trade_no, MoneyBilModel::DEL_cz)===0){///判断是否为充值订单
                          
                          $status = $this->chongzhisuccess($tradeData); 
                          LogModel::add("支付回调调用状态:" . $status);
                        
                     }else{ 
                        
                                            /**
                                             * type == 1 抢单 2预付款 3工资
                                             */
                                            if($type == 1){
                                                $status = $this->orderPayService->grapAlipay($channel,$tradeData);
                                            }elseif ($type == 2){
                                                $status = false;LogModel::add("支付回调调用失败:类型不支持".$type, LogModel::typeError);
                                            }elseif ($type == 3){
                                                $status = false;LogModel::add("支付回调调用失败:类型不支持".$type, LogModel::typeError);
                                            }else{
                                                $status = false;LogModel::add("支付回调调用失败:类型不支持".$type, LogModel::typeError);
                                            }
                         }
                         
                LogModel::add("支付回调:".$status);
                if($status){
                    $status='success';
                }else{
                     LogModel::add("支付回调调用事务失败:" . $this->msgerror, LogModel::typeError);
                    LogModel::add("支付回调调用失败:".$this->orderPayService->error, LogModel::typeError);
                }
                return $status;
            }

        } catch (\Exception $e) {
            LogModel::add('pay:alipay:' . $e->getMessage());
            info('pay:alipay:' . $e->getMessage());
        }
        return 'fail';
    }
    
    
    private $msgerror='';
    
    /**
     * 用户充值成功,让用户余额累加
    */
    private function chongzhisuccess($tradeData){
            $notify= json_encode($tradeData);
                LogModel::add("grapAlipay:" .$notify);
                $out_trade_no = $tradeData['out_trade_no'];
            
          try {
                     DB::beginTransaction();
                   
                     $MoneyBilModel = MoneyBilModel::where('out_trade_no', $out_trade_no)
                        // ->select([ 'status','out_trade_no','uid'  ])
                         ->first();
                      
                     if($MoneyBilModel){
                         
                         if($MoneyBilModel->status==MoneyBilModel::status_Success){ //如果已经支付过了,不再修改
                              DB::rollback(); 
                              return true;
                         }
                         
                         $MoneyBilModel->status= MoneyBilModel::status_Success;
                         $MoneyBilModel->notify=$notify;
                         $MoneyBilModel->play_time=time();
                         $MoneyBilModel->out_trade_no_play=$tradeData['trade_no']??'';
                         if(!$MoneyBilModel->save()){
                              DB::rollback();
                              $this->msgerror='保存订单状态错误'.$MoneyBilModel->uid;
                              return false;
                         }
                             
                         $userCount= \App\Models\User\UserModel::where(['id'=>$MoneyBilModel->uid])->increment('money',$MoneyBilModel->money);
                         if($userCount!==1){
                              DB::rollback();
                              $this->msgerror='更新用户余额错误'.$MoneyBilModel->uid;
                              return false;
                         }
                         DB::commit();
                        return true;
                     }else{
                         DB::rollback();
                              $this->msgerror='查找订单错误'.$out_trade_no.',UID'.$MoneyBilModel->uid;
                              return false;
                     }
                } catch (\Exception $e) {
                    $this->msgerror=$e->getMessage();
                    DB::rollback();
                    \Log::error($e->getMessage()); 
                    return false;
                }
    }
    
    
    
    
    
    
    
    

    /**
     * 支付宝退款
     * @throws \Exception
     */
    public function refundAlipayOrder(Request $request)
    {
        $oid = intval($request->input('oid', 0));;

        //调用方法
        try {
            $result = $this->orderPayService->alipayRefund($oid);

            if ($result) {

                return 'success';
            }

        } catch (\Exception $e) {
            info('退款失败:'.$e->getMessage());
        }
    }

    /**
     * 支付宝支付成功页面  TODO
     */
    public function success()
    {
       // exit('fdsag');
       return redirect(Fun::$HOST. '/h5/order/orderDocking.html');
       // return view('paysuccess');
    }
}
